package com.huaxin.hxmodulerabbitmq.listener;

import com.huaxin.feignclient.websocket.WebsocketClient;
import com.huaxin.feignclient.websocket.models.SendMessageRequest;
import com.huaxin.hxmodulerabbitmq.config.RabbitConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import com.huaxin.hxmodulerabbitmq.moels.Message;

@Component
@Slf4j
@RequiredArgsConstructor
public class MessageListener {

    private final WebsocketClient websocketClient;

    /**
     * 监听 RabbitMQ 消息队列
     */
    @RabbitListener(
            queues = RabbitConfig.MESSAGE_QUEUE,
            containerFactory = "rabbitListenerContainerFactory"
    )
    public void handleMessage(Message message) {
        log.info("📨 收到消息: {}", message);

        try {
            SendMessageRequest request = new SendMessageRequest();
            request.setContent(message.getContent());
            request.setTo(message.getTo());
            if (StringUtils.isBlank(request.getTo())) {
                websocketClient.broadcastMessage(request);
            } else {
                websocketClient.sendToClient(request);
            }

        } catch (Exception e) {
            log.error("推送消息失败", e);
            // 可以记录到数据库或发告警
            throw e; // 触发重试机制
        }
    }
}
